package listener;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

@WebListener
public class UserCountListener implements  HttpSessionListener {

    public UserCountListener() {
    }

        //创建session监听： 看你的一举一动
//一旦创建Session就会触发一次这个事件！
        @Override
        public void sessionCreated(HttpSessionEvent se) {
            ServletContext ctx = se.getSession().getServletContext();
            Integer userCount = (Integer) ctx.getAttribute("userCount");
            HttpSession session = se.getSession();if (userCount == null) {
                userCount = 1;
            } else {
                userCount = userCount + 1;
            }
            ctx.setAttribute("userCount", userCount);
        }
    //销毁session监听
//一旦销毁Session就会触发一次这个事件！
    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        ServletContext ctx = se.getSession().getServletContext();
        Integer userCount = (Integer) ctx.getAttribute("userCount");
        if (userCount == null) {
            userCount = 0;
        } else {
            userCount = userCount - 1;
        }
        ctx.setAttribute("userCount", userCount);
    }
}
